import { _decorator, Component, Node, Prefab, instantiate, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BlocksMap')
export class BlocksMap extends Component {

    @property({ type: Prefab })
    public boxPrefab: Prefab | null = null;

    lastIndexY: number = 0;
    speed: number = 3.2

    moving: boolean = false

    private _currentPos: Vec3 = new Vec3(0,0,0);

    start() {

    }

    update(deltaTime: number) {
        if(this.moving){
            this.node.getPosition(this._currentPos)
            this._currentPos.y = this._currentPos.y - this.speed
            this.node.setPosition(this._currentPos)
            setTimeout(()=>{
                if(this.lastIndexY + this._currentPos.y < 1000){
                    this.genOneRow()
                }
            })
            this.speed += 0.002
        }
    }

    /**
     * 生成规则：左边一个右边一个
     * index(-144 -46.5 46.5 144)
     */
    genOneRow() {
        this.node.addChild(this.randomNum() ? this.buildNode(-144, this.lastIndexY) : this.buildNode(-50, this.lastIndexY))
        this.node.addChild(this.randomNum() ? this.buildNode(144, this.lastIndexY) : this.buildNode(50, this.lastIndexY))
        this.lastIndexY += 250
    }

    buildNode(x: number, y: number) {
        const node = instantiate(this.boxPrefab)
        node.setPosition(x, y)
        return node
    }

    randomNum(): boolean {
        return Math.random() - 0.5 > 0
    }

    init(){
        this.speed = 1
        this.node.removeAllChildren()
        this.node.setPosition(0,0)
        this.lastIndexY = 0
        for (let i = 0; i < 10; i++) {
            this.genOneRow()
        }
        setTimeout(()=>{
            this.startMove()
        }, 1000)
    }

    startMove(){
        this.moving = true
    }

    stop(){
        this.moving = false
    }
}

